package com.yu.demo.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yu.demo.commons.ex.ErrorHandler;
import com.yu.demo.commons.result.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.IOException;

/**
 * @Description: 全局结果集处理
 * @Author: WengYu
 */
@RestControllerAdvice
public class ResultResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 是否拦截，ture拦截 false不拦截
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (o instanceof ErrorHandler) {
            ErrorHandler errorHandler = (ErrorHandler) o;
            return Result.fail(errorHandler.getCode(),errorHandler.getMessage());
        }
        if (o instanceof String) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Result result = Result.success(o);
                return objectMapper.writeValueAsString(result);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return Result.success(o);
    }
}
